package com.employment.security;

import com.employment.dao.UserMapper;
import com.employment.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Spring Security用户详情服务实现类
 * 
 * @author Employment System
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 支持用户名、邮箱、手机号登录
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            user = userMapper.selectByEmail(username);
        }
        if (user == null) {
            user = userMapper.selectByPhone(username);
        }

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        return new UserPrincipal(user);
    }

    /**
     * 根据用户ID加载用户信息
     */
    public UserDetails loadUserByUserId(Long userId) {
        User user = userMapper.selectOneById(userId);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + userId);
        }
        return new UserPrincipal(user);
    }
}